/*
 * 版权所有 (c) 2022-2099 TBIT。保留所有权利。
 */

package com.tbit.common.utils;

import cn.hutool.core.util.StrUtil;

/**
 * @author lmy
 * @ClassName MACUtils
 * @Description mac生成工具类
 * @date 2021/10/8 16:26
 * @Version 1.0
 */
public class MACUtils {

    // 正则表达式，支持冒号分隔的MAC地址，也支持无分隔符的MAC地址
    // 注意：这个正则表达式假设MAC地址中的每个十六进制数都是有效的（00-FF）
    private static final String MAC_ADDRESS_PATTERN =
            "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$";


    public static String getMacFromCode(String code) {
        try {
            long num = Long.parseLong(code);
            String mac = Long.toHexString(num).toUpperCase();

            if (mac.length() > 12) {
                return null;
            }

            mac = String.format("%12s", mac).replace(' ', '0');

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i <= 10; i += 2) {
                sb.append(mac, i, i + 2);
                if (i < 10) {
                    sb.append(":");
                }
            }
            return sb.toString();

        } catch (NumberFormatException e) {
            return null;
        }
    }

    public static String getCodeFromMac(String mac) {
        return StrUtil.isEmpty(mac)
                ? mac
                : String.valueOf(Long.parseLong(mac.replace(":", ""), 16));
    }

    public static boolean isMac(String str) {
        return StrUtil.isNotBlank(str) && str.matches(MAC_ADDRESS_PATTERN);
    }


    /**
     * 00 90 03 06 7
     * FF:7F:06:03:90:00
     *
     * @param mno
     * @return mac
     */
    private static String mac(String mno) {
        char[] chars = mno.toCharArray();
        if (chars.length == 9) {
            return String.format("FF:%sF:%s%s:%s%s:%s%s:%s%s", chars[8], chars[6], chars[7], chars[4], chars[5], chars[2], chars[3], chars[0], chars[1]);
        }
        return "error:" + mno;
    }

    public static void main(String[] args) {
        System.out.println("019011088=" + mac("019011088"));
        System.out.println("009280675=" + mac("009280675"));
        System.out.println("009265474=" + mac("009265474"));

        System.out.println(getMacFromCode("009265474"));
        System.out.println(getMacFromCode("0"));
    }
}
